<template>
  <div class="dicom-file-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>DICOM文件列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="fetchDicomFiles" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="success" @click="showUploader = true">
              <el-icon><Upload /></el-icon>
              上传文件
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
          <el-form-item label="患者ID">
            <el-input 
              v-model="searchForm.patientId" 
              placeholder="请输入患者ID" 
              clearable
            />
          </el-form-item>
          <el-form-item label="模态类型">
            <el-select 
              v-model="searchForm.modality" 
              placeholder="请选择模态类型" 
              clearable
            >
              <el-option label="所有类型" value="" />
              <el-option label="US" value="US" />
              <el-option label="CT" value="CT" />
              <el-option label="MRI" value="MRI" />
              <el-option label="CR" value="CR" />
              <el-option label="DX" value="DX" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 文件列表表格 -->
      <vxe-table
        :data="dicomFiles"
        :loading="loading"
        border
        stripe
        highlight-hover-row
        class="file-table"
      >
        <vxe-column type="seq" width="60" title="#" />
        <vxe-column field="filename" title="文件名" min-width="200">
          <template #default="{ row }">
            <span class="filename">{{ row.filename }}</span>
          </template>
        </vxe-column>
        <vxe-column field="PatientID" title="患者ID" width="120" />
        <vxe-column field="PatientName" title="患者姓名" width="150" />
        <vxe-column field="Modality" title="模态类型" width="100" />
        <vxe-column field="hasJpeg" title="JPEG状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.hasJpeg ? 'success' : 'warning'">
              {{ row.hasJpeg ? '已转换' : '未转换' }}
            </el-tag>
          </template>
        </vxe-column>
        <vxe-column field="actions" title="操作" width="250">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewImages(row)"
              :disabled="!row.hasJpeg"
            >
              查看图像
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="extractFrames(row)"
              :loading="row.extracting"
            >
              拆解帧
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteFile(row)"
            >
              删除
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 上传组件弹窗 -->
    <el-dialog
      v-model="showUploader"
      title="上传DICOM文件"
      width="600px"
      destroy-on-close
    >
      <DicomUploader @upload-complete="handleUploadComplete" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Upload } from '@element-plus/icons-vue'
import DicomUploader from './DicomUploader.vue'
import api from '@/utils/api'

const router = useRouter()

// 响应式数据
const dicomFiles = ref([])
const loading = ref(false)
const showUploader = ref(false)

// 搜索表单
const searchForm = reactive({
  patientId: '',
  modality: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 获取DICOM文件列表
const fetchDicomFiles = async () => {
  loading.value = true
  try {
    const response = await api.getDicomFiles()
    dicomFiles.value = response.data || []
    pagination.total = dicomFiles.value.length
    
    // 为每个文件添加拆解状态
    dicomFiles.value.forEach(file => {
      file.extracting = false
    })
  } catch (error) {
    ElMessage.error('获取文件列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = async () => {
  loading.value = true
  try {
    const response = await api.searchDicomFiles(searchForm.patientId, searchForm.modality)
    dicomFiles.value = response.data || []
    pagination.total = dicomFiles.value.length
  } catch (error) {
    ElMessage.error('搜索失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.patientId = ''
  searchForm.modality = ''
  fetchDicomFiles()
}

// 查看图像
const viewImages = (row) => {
  router.push(`/enhanced-image-viewer/${row.filename}`)
}

// 拆解帧
const extractFrames = async (row) => {
  try {
    row.extracting = true
    await api.extractDicomFrames(row.filename)
    ElMessage.success('帧拆解请求已提交')
    
    // 重新获取文件列表以更新状态
    setTimeout(() => {
      fetchDicomFiles()
    }, 2000)
  } catch (error) {
    ElMessage.error('帧拆解失败: ' + error.message)
  } finally {
    row.extracting = false
  }
}

// 删除文件
const deleteFile = (row) => {
  ElMessageBox.confirm(
    `确定要删除文件 "${row.filename}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.deleteDicomFile(row.filename)
      ElMessage.success('文件删除成功')
      // 重新获取文件列表
      fetchDicomFiles()
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理上传完成
const handleUploadComplete = () => {
  showUploader.value = false
  fetchDicomFiles()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 这里可以添加重新获取数据的逻辑
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  // 这里可以添加重新获取数据的逻辑
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDicomFiles()
})
</script>

<style scoped>
.dicom-file-list {
  padding: 20px;
}

.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-table {
  margin-bottom: 20px;
}

.filename {
  color: #409eff;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}
</style>